package com.gitee.wsl.common.ui.ext

import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.ImageBitmapConfig
import androidx.compose.ui.graphics.asComposeImageBitmap
import androidx.compose.ui.graphics.asSkiaBitmap
import androidx.compose.ui.graphics.toComposeImageBitmap
import org.jetbrains.skia.Image

actual fun ImageBitmap.Companion.fromBytes(bytes: ByteArray): ImageBitmap {
    return Image.makeFromEncoded(bytes).toComposeImageBitmap()
}

fun ByteArray.toImageBitmap(): ImageBitmap = Image.makeFromEncoded(this).toComposeImageBitmap()

actual fun ImageBitmap.toByteArray(): ByteArray? {
    return Image.makeFromBitmap(this.asSkiaBitmap()).encodeToData()?.bytes
}

actual fun ImageBitmap.Companion.fromPixmap(
    width: Int,
    height: Int,
    colors: IntArray
)  : ImageBitmap {

    val bgra = ByteArray(colors.size * 4) {
        colors[it / 4].ushr((it % 4) * 8).toByte()
    }

    return ImageBitmap(width, height, ImageBitmapConfig.Argb8888)
        .asSkiaBitmap().apply { installPixels(bgra) }
        .asComposeImageBitmap()
}